package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.OnloadingMoreListener;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.dialog.AlertDialogUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.activity.ChooseUnitActivity;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.ClassGvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.adapter.QuestionBankAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.ClassInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.QuestionBankInfo;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassPoputil;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 题库练习
 */
public class TeacherQuestionBankActivity extends BaseActivity implements OnloadingMoreListener, SrfManager.OnPullRefreshListener {

    @BindView(R.id.main)
    RelativeLayout rlMain;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.lv_class)
    ImageView lvClass;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srf)
    SmartRefreshLayout srf;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoadingView;
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;

    //分页
    private int page = 0;

    //适配器
    private QuestionBankAdapter adapter;

    //空视图
    private View emptyView;

    //数据源
    private List<QuestionBankInfo.DataBean> oldDatas;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted = true;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    private int isClassStudents = 0;

    //学生分析重新推送后页面更新的标识
    public static final int UPDATEPAGE = 0X990;


    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_question_bank;
    }

    @Override
    protected void init() {

        //沉浸状态栏
        initStateBar();

        //设置标题
        initTitle();

        //初始化下拉刷新控件
        initSrf();

        //请求服务器数据获取班级列表
        httpClass();

    }

    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, this);
    }


    /**
     * 设置标题
     */
    private void initTitle() {
        tvTitle.setText("题库练习");
    }


    /**
     * 请求班级里列表数据
     */
    private void httpClass() {
        ClassUtil.httpClass(rlLoadingView, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //证明有班级
                lvEdit.setVisibility(View.VISIBLE);
                lvClass.setVisibility(View.VISIBLE);


                //改变加载完成的标记
                isLoadClassCompleted = true;

                //设置数据
                initRv();

                //请求页面列表数据
                httpPageData(popSelectedPos, BqaManager.NORML);

                //保存班级
                SPUtil.put(TeacherQuestionBankActivity.this, SpKeys.TEACHERCLASS, classInfos.get(popSelectedPos).getNum() + "");

            }

            @Override
            public void hasNoData() {
                //没有班级,不显示顶部的切换班级的按钮和
                lvEdit.setVisibility(View.INVISIBLE);
                lvClass.setVisibility(View.INVISIBLE);
            }
        });
    }

    /**
     * 设置列表的方法
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMessage = emptyView.findViewById(R.id.tv_content);
        tvMessage.setText("暂无练习内容");
        adapter = new QuestionBankAdapter(this, R.layout.teacher_rv_question_bank, oldDatas);

        //设置条目的长按事件
        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                //获取推送状态
                String push_state = oldDatas.get(position).getPush_state();
                String pushTime = oldDatas.get(position).getPush_time();

                if ("0".equals(push_state)) {
                    //未布置可以删除
                    showDeletePop(position);
                } else {
                    //已布置未推送可以删除
                    if (!DateUtils.getTimeSize(pushTime)) {
                        //未推送
                        showDeletePop(position);
                    }
                }

                return false;
            }
        });

        //设置图形显示答题人数的控件的点击事件
        adapter.setOnArcViewClickListener(new QuestionBankAdapter.OnArcViewClickListener() {
            @Override
            public void onClick(QuestionBankInfo.DataBean item) {
                //弹框显示已做人数和未做人数的详细信息
                showDetailsStPop(item);
            }
        });
    }

    /**
     * 弹框显示已答题和未答题的详细信息
     *
     * @param item
     */
    private void showDetailsStPop(final QuestionBankInfo.DataBean item) {
        PopUpManager.showPop(this, R.layout.pop_show_details_stu, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                ImageView lvClose = view.findViewById(R.id.lv_close);
                TextView tvCommit = view.findViewById(R.id.tv_commit_word);
                TextView tvNoCommit = view.findViewById(R.id.tv_no_commit_word);

                //未交练习的学生
                List<String> notask_stu = item.getNotask_stu();
                if (null == notask_stu || notask_stu.size() == 0) {
                    //没有学生交练习
                    tvNoCommit.setText("无");

                } else {
                    tvNoCommit.setText(getStuString(notask_stu));
                }

                //已交练习的学生
                List<String> taskStu = item.getTask_stu();
                if (null == taskStu || taskStu.size() == 0) {
                    //没有学生交练习
                    tvCommit.setText("无");

                } else {
                    tvCommit.setText(getStuString(taskStu));
                }

                lvClose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });
            }
        });
    }

    /**
     * 返回名单的拼接字符串
     *
     * @param stus
     * @return
     */
    public String getStuString(List<String> stus) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < stus.size(); i++) {
            if (i != stus.size() - 1) {
                sb.append(stus.get(i));
                sb.append("、");
            } else {
                sb.append(stus.get(i));
            }
        }

        return sb.toString();
    }

    /**
     * 删除练习的弹框
     */
    private void showDeletePop(final int positon) {

        AlertDialogUtil.showAlertDialog(true, this, "确定删除此条练习吗?", new AlertDialogUtil.onListener() {
            @Override
            public void onClickOk() {
                CustomDialogManager.show(TeacherQuestionBankActivity.this, "删除中...");

                Map<String, String> map = new HashMap<>();
                map.put("jobmsg", "7");
                map.put("ttel", AccountUtils.getAccount(TeacherQuestionBankActivity.this));
                map.put("classnum", classInfos.get(popSelectedPos).getNum() + "");
                map.put("total", oldDatas.get(positon).getTotal());
                map.put("unit", oldDatas.get(positon).getUnit());

                Log.i("test", "classnum=" + classInfos.get(popSelectedPos).getNum() + "&total=" +
                        oldDatas.get(positon).getTotal() + "&unit=" + oldDatas.get(positon).getUnit());

                HttpUtils.post(HttpAddress.DELEWORK, map, this, new HttpCallBack<ResultInfo>() {
                    @Override
                    public void onSuccess(ResultInfo resultInfo) {
                        CustomDialogManager.dissmiss();
                        if ("1".equals(resultInfo.getState()) || "200".equals(resultInfo.getState())) {
                            ToastUtils.showShort("删除成功");
                            httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
                        } else {
                            ToastUtils.showShort("删除失败");
                        }

//                        adapter.notifyItemRemoved(positon);
                    }

                    @Override
                    public void onError(String e) {
                        CustomDialogManager.dissmiss();
                        ToastUtils.showShort("删除失败");
                    }
                });

            }

            @Override
            public void onClickDismiss() {

            }
        });
    }


    /**
     * 页面控件点击事件
     */
    @OnClick({R.id.iv_back, R.id.lv_edit, R.id.lv_class})
    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:


                if (classInfos != null && classInfos.size() != 0) {
                    //保存班级
                    SPUtil.put(this, SpKeys.TEACHERCLASS, classInfos.get(popSelectedPos).getNum() + "");
                }

//                if("2".equals(AccountUtils.getRole(this))
//                        && 1 == isClassStudents){
//                    //班级中没有学生
//                    AlertDialogUtil.showAlertDialogSimple(false,
//                            this,"该班级暂时没有学生，创建学生后才可以布置练习",null);
//                    return;
//                }

                //选择单元
                UiUtils.startActivity(this, ChooseUnitActivity.class);

                break;
            case R.id.lv_class:
                //选择班级
                if (isLoadClassCompleted) {
                    //弹出选择班级的PopUpWindow
                    showClassPop();
                } else {
                    //没加载完成
                    SnackbarUtil.ShortSnackbar(rlMain, Constants.LOADING, 0).show();
                }
                break;
        }
    }

    /**
     * 弹出展示班级列表的方法
     */
    private void showClassPop() {

        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {

                //记录当前点击条目的位置
                popSelectedPos = pos;

                //保存班级
                SPUtil.put(TeacherQuestionBankActivity.this, SpKeys.TEACHERCLASS, classInfos.get(popSelectedPos).getNum() + "");

                //请求页面数据
                httpPageData(popSelectedPos, BqaManager.NORML);


            }
        });
    }


    /**
     * 请求页面数据的方法
     *
     * @param popSelectedPos
     */
    private void httpPageData(int popSelectedPos, final int method) {
        if (method == BqaManager.PULLREFRESH || method == BqaManager.NORML) {
            page = 0;
        } else {
            page++;
        }

        Map<String, String> map = new HashMap<>();
        map.put("jobmsg", "3");
        map.put("ttel", AccountUtils.getAccount(this));
        map.put("classnum", classInfos.get(popSelectedPos).getNum() + "");
        map.put("pages", page + "");
        map.put("sizi", 10 + "");

        Log.i("test", classInfos.get(popSelectedPos).getNum() + "");

        HttpUtils.post(HttpAddress.TKZY, map, this, new HttpCallBack<QuestionBankInfo>() {
            @Override
            public void onSuccess(QuestionBankInfo info) {
                if (rlLoadingView != null && rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (null != info && "1".equals(info.getState())) {

                    //返回成功
                    List<QuestionBankInfo.DataBean> newDatas = info.getData();
                    if (newDatas != null) {
                        if (method == BqaManager.NORML) {
                            oldDatas.clear();
                            oldDatas.addAll(newDatas);
                            BqaManager.setRv(emptyView, TeacherQuestionBankActivity.this, adapter, rv, TeacherQuestionBankActivity.this);
                        } else {
                            //更新数据
                            BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                        }
                    }
                } else {
                    ToastUtils.showShort("返回器返回异常,错误码是:" + info.getState());
                    Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                }
            }

            @Override
            public void onError(String e) {
                BqaManager.setErrorNet(rlLoadingView, srf, method, adapter);
                Log.i("test", "获取题库练习数据异常");
            }
        });
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        httpPageData(popSelectedPos, BqaManager.LOADINDGMORE);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
    }


    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);

        if (busInfo != null) {
            //布置练习成功或者草稿保存成功后刷新界面
            if (busInfo.type == com.ycsj.goldmedalnewconcept.teacher.activity.TeacherCreateHomeworkActivity.SUBMITSUC || busInfo.type == com.ycsj.goldmedalnewconcept.teacher.activity.TeacherTKAssignHomeworkActivity.SUBMITREF) {
                httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
            }

            //学生分析界面推送后的更新标识
            if (busInfo.type == UPDATEPAGE) {
                //获取更新的位置
                int positon = busInfo.tkPos;

                //获取再次推送的学生姓名
                String name = busInfo.stuName;

                QuestionBankInfo.DataBean dataBean = oldDatas.get(positon);

                //获取未交练习的学生
                List<String> notask_stu = dataBean.getNotask_stu();

                //获取已交学生的练习
                List<String> taskStu = dataBean.getTask_stu();

                if (notask_stu != null && taskStu != null) {
                    taskStu.remove(name);
                    notask_stu.add(name);
                }

                //通知当前位置的适配器刷新
                adapter.notifyItemChanged(positon);
            }
        }
    }
}
